import React, { useEffect } from 'react';
import { eventTrack } from '@/utils/track';
import { connect } from 'umi';
import { Form, Modal, Row, Col, ConfigProvider } from 'antd';
import { QuickForm } from 'vv-frontend-components';
// import { SearchInput, TreeSelectForm } from '@/components/UserForm';
import { SearchInput, SelectForm, CascaderForm } from '@/components/UserForm'; // 模糊查询
import { getCandidateList } from '@/services/myRecruit/candidate';
import { getApplyjob } from '@/services/components/userform';
import request from '@/utils/request';
import clone from 'lodash/clone';

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 }
};
// 候选人下拉
// const renderCandidateOption = candidateList => candidateList.map(item => <Option value={item.dictKey}>{item.dictName}</Option>);
// 应聘职位下拉
// const renderPostOption = postApplyList => postApplyList.map(item => <Option value={item.dictKey}>{item.dictName}</Option>);
// 选择候选人模糊查询 应聘职位下拉

let departmentId = '';
const departmentChange = value => {
    departmentId = clone(value).pop();
};

const addConfig = (form, companyId) => [
    {
        field: 'talentCode',
        label: '选择候选人',
        key: 'talentCode',
        props: {
            ...formItemLayout
        },
        component: (
            <SearchInput
                params={
                    {
                        // talentName: localCompanyId
                    }
                }
                requireParam={['talentName']}
                getData={params =>
                    getCandidateList(params).then(res => {
                        if (res && res.code === 10000) {
                            return res.data || [];
                        }
                        return [];
                    })
                }
                selectProps={{
                    placeholder: '请选择候选人',
                    style: { minWidth: 200 },
                    allowClear: true
                }}
                fieldsName={{
                    value: 'talentCode',
                    title: 'talentName',
                    extraParams: 'talentName',
                    candidate: 'candidate'
                }}
                // onChange={this.handleSelect}
            />
        ),
        config: {
            // initialValue: postDetail.postType ? postDetail.postType : [],
            rules: [{ required: true, message: '请选择候选人' }]
        }
    },
    {
        field: 'departmentId',
        label: '应聘部门',
        key: 'departmentId',
        props: {
            ...formItemLayout
        },
        component: (
            <CascaderForm
                getData={() =>
                    request('/api/org/v1/functional/list').then(res => {
                        if (res && res.code === 10000 && res.data) {
                            return res.data || [];
                        }
                        return [];
                    })
                }
                fieldsName={{
                    selectValue: 'id',
                    selectTitle: 'departmentName',
                    selectChildren: 'children'
                }}
                onChange={v => {
                    departmentChange(v);
                    form.resetFields('recruitCode');
                }}
                selectProps={{
                    placeholder: '请选择部门',
                    changeOnSelect: true,
                    expandTrigger: 'hover'
                }}
            />
        ),
        config: {
            // initialValue: postDetail.postType ? postDetail.postType : [],
            rules: [{ required: true, message: '请选择应聘部门' }]
        }
    },
    {
        field: 'recruitCode',
        label: '应聘职位',
        key: 'recruitCode',
        props: {
            ...formItemLayout
        },
        component: (
            <SelectForm
                params={{ companyId: departmentId ? '' : companyId, departmentId, recruitSchedule: 'recruit_hiring' }}
                // requireParam={['companyId ']}
                getData={params =>
                    getApplyjob(params).then(res => {
                        if (res && res.code === 10000 && res.data) {
                            return res.data || [];
                        }
                        return [];
                    })
                }
                fieldsName={{
                    selectValue: 'recruitCode',
                    selectTitle: 'recruitName'
                }}
                // onChange={this.companyChange}
                selectProps={{
                    placeholder: '请选择应聘职位',
                    style: { minWidth: 200 }
                }}
            />
        ),
        config: {
            // initialValue: postDetail.postType ? postDetail.postType : [],
            rules: [{ required: true, message: '请选择应聘职位' }]
        }
    }
];
const AddCandidate = ({
    Visible,
    params, // 传入的参数
    onOk, // 关闭模态框
    onCancel, // 关闭模态框
    dispatch,
    form,
    common
}) => {
    const { fetchList } = params;
    const { candidateList, postApplyList } = common;

    const user = localStorage.getItem('user');
    const { companyId } = user ? JSON.parse(user) : {};

    // 获取下拉项数据
    useEffect(() => {
        if (candidateList === []) {
            // 候选人姓名字典
            dispatch({
                type: 'common/fetchCandidateList',
                payload: {
                    code: 'postType'
                }
            });
        }
        if (postApplyList === []) {
            // 应聘职位列表
            dispatch({
                type: 'common/fetchPostApplyList',
                payload: {}
            });
        }
    }, [candidateList, postApplyList]);

    // 提交候选人
    const handleOk = closeModel => {
        form.validateFields((err, values) => {
            if (!err) {
                dispatch({
                    type: 'common/addCandidate',
                    payload: {
                        ...values,
                        departmentId,
                        talentCode: values.talentCode.split('-')[0]
                        // id: postId
                    },
                    success: () => {
                        fetchList({ pageNo: 1 });
                    }
                });
                // 关闭模态框
                closeModel();
                form.resetFields();
                // 埋点
                eventTrack({
                    eventName: 'personal_my_recruit_candidate_add_submit_click',
                    eventProps: { label: '添加候选人-确定', status: 0 }
                });
            } else {
                eventTrack({
                    eventName: 'personal_my_recruit_candidate_add_submit_click',
                    eventProps: { label: '添加候选人-确定', status: 1, error_info: JSON.stringify(err) }
                });
            }
        });
    };
    return (
        <Modal
            title="添加候选人"
            width="750px"
            visible={Visible}
            // confirmLoading={loading}
            onOk={() => {
                handleOk(onOk);
            }}
            onCancel={() => {
                onCancel();
                // 埋点
                eventTrack({
                    eventName: 'personal_my_recruit_candidate_add_cancel_click',
                    eventProps: { label: '添加候选人-取消' }
                });
                form.resetFields();
                departmentId = '';
            }}
        >
            {/* <Spin spinning={loading}> */}
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <Form layout="horizontal">
                    <QuickForm config={addConfig(form, companyId)} form={form} />

                    <Row>
                        <Col span={6}></Col>
                        <Col span={14}>
                            注：该人才将成为选择的应聘职位的候选人，并针对该职位开展筛选、面试等招聘工作。
                        </Col>
                    </Row>
                </Form>

                {/* </Spin> */}
            </ConfigProvider>
        </Modal>
    );
};

export default connect(({ common, loading }) => ({
    common,
    loading
}))(Form.create()(AddCandidate));
